package com.euq.mq;

import com.euq.entity.OperationLog;
import com.euq.mapper.OperationLogMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RocketMQMessageListener(topic = "operation-topic", consumerGroup = "operation-consumer-group")
public class OperationConsumer implements RocketMQListener<String> {

    private static final Logger log = LoggerFactory.getLogger(OperationConsumer.class);

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onMessage(String message) {
        log.info("接收到操作日志消息：{}", message);
        try {
            OperationLog operationLog = objectMapper.readValue(message, OperationLog.class);
            operationLog.setCreateTime(LocalDateTime.now());
            operationLogMapper.insertOperationLog(operationLog);
            log.info("操作日志已保存：{}", operationLog);
        } catch (Exception e) {
            log.error("操作日志消费失败，消息内容：{}", message, e);
        }
    }
}
